package gui

import (
	"fmt"
	"os"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing/object"
)

type RepositoryUI struct {
	TableRef         *widget.Table
	DouFuJingLingBtn *widget.Button
	CopyBtn          *widget.Button
	EditBtn          *widget.Button
	DeleteBtn        *widget.Button
}

var repositoryUI RepositoryUI

// 创建表格界面
func (ui *MainWindow) MakeRepositoryUI(win fyne.Window, name string) fyne.CanvasObject {
	/* 工具栏 */
	pullBtn := widget.NewButton("拉取", func() {})
	pushBtn := widget.NewButton("推送", func() {})
	branchBtn := widget.NewButton("分支", func() {})
	mergeBtn := widget.NewButton("合并", func() {})
	labelBtn := widget.NewButton("标签", func() {})
	refreshBtn := widget.NewButton("刷新", func() {})
	repoSetBtn := widget.NewButton("仓库设置", func() {})

	pullBtn.OnTapped = func() {}
	pushBtn.OnTapped = func() {
		remoteName := TreeTabData[ui.CurrentSelectUID].Info.Remote_name
		// remotePath := TreeTabData[ui.CurrentSelectUID].Info.Remote_path

		/* // 检查仓库对象是否有效
		repo := ui.RepositoryList[ui.CurrentSelectUID].Repo
		if repo == nil {
			fmt.Println("错误: 仓库对象为nil")
			os.Exit(1)
		}

		// 检查是否是有效的git仓库
		_, err := repo.Head()
		if err != nil {
			fmt.Printf("验证仓库失败: %v\n", err)
			os.Exit(1)
		} */

		/* 			// 创建远程配置
		remoteName := "origin"
		remoteURL := "https://github.com/username/repository.git"

		// 添加远程
		_, err = repo.CreateRemote(&config.RemoteConfig{
			Name: remoteName,
			URLs: []string{remoteURL},
		})
		if err != nil {
			fmt.Printf("添加远程失败: %v\n", err)
			os.Exit(1)
		} */

		// 获取远程仓库
		remote, err := ui.RepositoryList[ui.CurrentSelectUID].Repo.Remote(remoteName)
		if err != nil {
			fmt.Printf("获取远程仓库失败: %v\n", err)
			os.Exit(1)
		}

		// 推送更改
		err = remote.Push(&git.PushOptions{
			RemoteName: remoteName,
			Auth:       nil, // 如果需要认证，可以在这里设置
		})
		if err != nil {
			fmt.Printf("推送失败: %v\n", err)
			os.Exit(1)
		}

		fmt.Println("推送成功!")
	}
	branchBtn.OnTapped = func() {}
	mergeBtn.OnTapped = func() {}
	labelBtn.OnTapped = func() {}
	headerLayout := container.NewHBox(pullBtn, pushBtn, branchBtn, mergeBtn, labelBtn, refreshBtn, repoSetBtn, widget.NewLabel(""))

	//======================start 已暂存文件 ======================
	storedList := ui.RepositoryList[ui.CurrentSelectUID].StoredFilesList
	fmt.Println("data:", storedList)
	icon := widget.NewIcon(nil)
	label := widget.NewLabel("Select An Item From The List")

	storedFilesList := widget.NewList(
		func() int {
			return len(storedList)
		},
		func() fyne.CanvasObject {
			return container.NewHBox(widget.NewIcon(theme.DocumentIcon()), widget.NewLabel("Template Object"))
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			if id == 5 || id == 6 {
				item.(*fyne.Container).Objects[1].(*widget.Label).SetText(storedList[id] + "\ntaller")
			} else {
				item.(*fyne.Container).Objects[1].(*widget.Label).SetText(storedList[id])
			}
			fmt.Println(storedList[id])
		},
	)
	storedFilesList.OnSelected = func(id widget.ListItemID) {
		label.SetText(storedList[id])
		icon.SetResource(theme.DocumentIcon())
	}
	storedFilesList.OnUnselected = func(id widget.ListItemID) {
		label.SetText("Select An Item From The List")
		icon.SetResource(nil)
	}
	/* storedFilesList.Select(125)
	storedFilesList.SetItemHeight(5, 50)
	storedFilesList.SetItemHeight(6, 50) */
	storedFilesLabel := widget.NewCard("", "已暂存文件", storedFilesList)
	storedFilesLayout := container.NewVBox(storedFilesLabel)
	//======================end 已暂存文件 ======================

	//======================start 未暂存文件 ======================
	notStoredList := ui.RepositoryList[ui.CurrentSelectUID].NotStoredFilesList
	fmt.Println("notStoredList:", notStoredList)
	icons := widget.NewIcon(nil)
	labels := widget.NewLabel("Select An Item From The List")

	notStoredFilesList := widget.NewList(
		func() int {
			return len(notStoredList)
		},
		func() fyne.CanvasObject {
			return container.NewHBox(widget.NewIcon(theme.DocumentIcon()), widget.NewLabel("Template Object"))
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			if id == 5 || id == 6 {
				item.(*fyne.Container).Objects[1].(*widget.Label).SetText(notStoredList[id] + "\ntaller")
			} else {
				item.(*fyne.Container).Objects[1].(*widget.Label).SetText(notStoredList[id])
			}
		},
	)
	notStoredFilesList.OnSelected = func(id widget.ListItemID) {
		labels.SetText(notStoredList[id])
		icons.SetResource(theme.DocumentIcon())
	}
	notStoredFilesList.OnUnselected = func(id widget.ListItemID) {
		labels.SetText("Select An Item From The List")
		icons.SetResource(nil)
	}
	notStoredFilesLabel := widget.NewCard("", "未暂存文件", notStoredFilesList)
	notStoredFilesLayout := container.NewVBox(notStoredFilesLabel)
	//======================end 未暂存文件 ======================

	//======================start 提交信息 ======================
	descInput := widget.NewEntry()
	descInput.SetPlaceHolder("描述信息")
	//多行输入
	descInput.MultiLine = true
	descInput.Wrapping = 2 // 开启自动换行
	submitBtn := widget.NewButton("提交", func() {
		// 获取工作树
		worktree, err := ui.RepositoryList[ui.CurrentSelectUID].Repo.Worktree()
		if err != nil {
			fmt.Printf("获取工作树失败: %v\n", err)
			os.Exit(1)
		}
		/* // 添加单个文件到暂存区
		info, err := worktree.Add(filePath)
		if err != nil {
			return fmt.Errorf("添加文件失败: %v", err)
		} */
		// 添加所有变更到暂存区（包括修改、新增和删除的文件）
		_, err = worktree.Add(".")
		if err != nil {
			fmt.Errorf("添加所有文件失败: %v", err)
			return
		}

		/* 	// 可以在提交前设置默认作者信息
		author := &object.Signature{
			Name:  "Your Name",
			Email: "your.email@example.com",
			When:  time.Now(),
		} */

		/* // 提交更改
		commit, err := worktree.Commit(descInput.Text, &git.CommitOptions{
			Author: &object.Signature{
				Name:  "Raymond",
				Email: "vteipjuq@163.com",
				When:  time.Now(),
			},
		})
		if err != nil {
			fmt.Printf("提交失败: %v\n", err)
			os.Exit(1)
		}

		fmt.Printf("提交成功: %s\n", commit) */
	})
	submitLayout := container.NewVBox(descInput, submitBtn)
	//======================start 提交信息 ======================
	rightLayout := container.NewVBox(headerLayout, storedFilesLayout, notStoredFilesLayout, submitLayout)
	/* // 使用 BorderLayout，滚动区域在中心，按钮在底部
	rightLayout := container.NewBorder(
		nil, // 顶部无元素
		nil, // 底部放置按钮
		nil, // 左侧无元素
		nil, // 右侧无元素
		container.NewVScroll(container.NewStack(rightVBoxLayout)), // 中心区域放置滚动内容
	)
	*/

	type History struct {
		Picture string
		Hash    string
		Author  string
		Message string
		Date    string
	}
	historyData := make([]History, 0)
	// 正常处理非空仓库
	// 获取 HEAD 引用
	ref, err := ui.RepositoryList[ui.CurrentSelectUID].Repo.Head()
	if err == nil {
		/* 	const (
			LogOrderDefault LogOrder = iota
			LogOrderDFS
			LogOrderDFSPost
			LogOrderBSF
			LogOrderCommitterTime // 按提交时间排序
		) */

		// 获取提交历史
		commitIter, err := ui.RepositoryList[ui.CurrentSelectUID].Repo.Log(&git.LogOptions{
			From: ref.Hash(),
			// Order: git.LogOrderDFS,
			// Limit: 10,
		})
		if err != nil {
			panic(err)
		}
		// 打印最近 5 个提交
		count := 0
		err = commitIter.ForEach(func(c *object.Commit) error {
			if count >= 5 {
				return fmt.Errorf("done") // 这会停止迭代
			}
			count++

			fmt.Println("Hash:", c.Hash)
			fmt.Println("Author:", c.Author.Name, "<"+c.Author.Email+">")
			fmt.Println("Date:", c.Author.When.Format("06-01-02 15:04"))
			fmt.Println("Message:", c.Message)
			fmt.Println("-----")
			historyData = append(historyData, History{Hash: c.Hash.String(), Author: c.Author.Name, Date: c.Author.When.Format("06-01-02 15:04"), Message: c.Message})
			return nil
		})

		if err != nil && err.Error() != "done" {
			panic(err)
		}
	} else {
		// 初始化仓库后为空
		// panic(err)
	}
	historyList := widget.NewList(
		func() int {
			return len(historyData)
		},
		func() fyne.CanvasObject {
			// row1 := container.NewHBox(widget.NewLabel("描述"), widget.NewLabel("Object"))
			// row2 := container.NewHBox(widget.NewLabel("作者"), widget.NewLabel("Object"))
			row1 := container.NewBorder(
				nil,                   // 顶部无元素
				nil,                   // 底部放置按钮
				widget.NewLabel("描述"), // 左侧无元素
				widget.NewLabel("描述"), // 右侧无元素
				nil,                   // 中心区域放置滚动内容
			)
			row2 := container.NewBorder(
				row1,                  // 顶部无元素
				nil,                   // 底部放置按钮
				widget.NewLabel("描述"), // 左侧无元素
				widget.NewLabel("描述"), // 右侧无元素
				nil,                   // 中心区域放置滚动内容
			)
			return container.NewHBox(widget.NewIcon(theme.DocumentIcon()), row2)
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			// item.(*fyne.Container).Objects[1].(*widget.Label).SetText(historyData[id].Message + "\ntaller")
			/* //描述
			item.(*fyne.Container).Objects[1].(*fyne.Container).Objects[0].(*fyne.Container).Objects[0].(*widget.Label).SetText(historyData[id].Message)
			//作者
			item.(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*fyne.Container).Objects[0].(*widget.Label).SetText(historyData[id].Author)
			item.(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*widget.Label).SetText(historyData[id].Date) */

			//描述
			// item.(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*fyne.Container).Objects[2].(*widget.Label).SetText(historyData[id].Message)

			hbox := item.(*fyne.Container).Objects[1]
			// 获取 row2 Border 容器
			row2 := hbox.(*fyne.Container)
			// 获取 "描述1"（来自 row1）
			row1 := row2.Objects[0].(*fyne.Container) // row1 是 row2 的顶部元素
			desc1 := row1.Objects[0].(*widget.Label)  // 左侧第三个元素是 "描述1"
			desc1.SetText(historyData[id].Message)

			desc2 := row2.Objects[1].(*widget.Label)
			desc2.SetText(historyData[id].Author)
			desc3 := row2.Objects[2].(*widget.Label)
			desc3.SetText(historyData[id].Date)

			/* //作者
			item.(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*fyne.Container).Objects[0].(*widget.Label).SetText(historyData[id].Author)
			item.(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*fyne.Container).Objects[1].(*widget.Label).SetText(historyData[id].Date)
			*/
		},
	)

	/* // 使用 BorderLayout，滚动区域在中心，按钮在底部
	allLayout := container.NewBorder(
		nil, // 顶部无元素
		nil, // 底部放置按钮
		container.NewVScroll(container.NewStack(historyList)), // 左侧无元素
		nil, // 右侧无元素
		container.NewVScroll(container.NewStack(rightLayout)), // 中心区域放置滚动内容
	) */

	// 创建水平分割容器
	allLayout := container.NewHSplit(container.NewVScroll(container.NewStack(historyList)), container.NewVScroll(container.NewStack(rightLayout)))
	allLayout.Offset = 0.25
	return allLayout
}
func getReverseCommitHistoryPaginated(repoPath string, pageSize int) ([]*object.Commit, error) {
	repo, err := git.PlainOpen(repoPath)
	if err != nil {
		return nil, err
	}

	ref, err := repo.Head()
	if err != nil {
		return nil, err
	}

	var allCommits []*object.Commit
	skip := 0

	for {
		// 获取一页提交
		commitIter, err := repo.Log(&git.LogOptions{
			From:  ref.Hash(),
			Order: git.LogOrderCommitterTime,
			/* Skip:  skip,
			Limit: pageSize, */
		})
		if err != nil {
			return nil, err
		}

		var pageCommits []*object.Commit
		err = commitIter.ForEach(func(c *object.Commit) error {
			pageCommits = append(pageCommits, c)
			return nil
		})
		if err != nil {
			return nil, err
		}

		// 如果获取不到更多提交，退出循环
		if len(pageCommits) == 0 {
			break
		}

		// 反转当前页的提交顺序
		for i, j := 0, len(pageCommits)-1; i < j; i, j = i+1, j-1 {
			pageCommits[i], pageCommits[j] = pageCommits[j], pageCommits[i]
		}

		allCommits = append(pageCommits, allCommits...)
		skip += pageSize
	}

	return allCommits, nil
}

// 推送到远程仓库
/* func pushChanges(repo *git.Repository) error {
	privateKeyPath := os.Getenv("HOME") + "/.ssh/id_rsa" // SSH私钥路径
	username := "git"
	auth, err := publicKeyAuth(privateKeyPath, username)
	if err != nil {
		return fmt.Errorf("SSH认证失败: %v", err)
	}

	err = repo.Push(&git.PushOptions{
		RemoteName: "origin",
		Auth:       auth,
	})
	if err != nil {
		if err == git.NoErrAlreadyUpToDate {
			fmt.Println("仓库已是最新状态")
			return nil
		}
		return fmt.Errorf("推送失败: %v", err)
	}

	return nil
} */

// 创建SSH公钥认证
/* func publicKeyAuth(privateKeyPath, username string) (transport.AuthMethod, error) {
	// 读取私钥文件
	key, err := os.ReadFile(privateKeyPath)
	if err != nil {
		return nil, fmt.Errorf("读取私钥失败: %v", err)
	}

	// 创建SSH认证
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		return nil, fmt.Errorf("解析私钥失败: %v", err)
	}

	auth := &ssh.PublicKeys{
		User:   username,
		Signer: signer,
	}

	// 禁用主机密钥检查（仅用于测试环境）
	// 生产环境中应使用适当的主机密钥验证
	auth.HostKeyCallback = ssh.InsecureIgnoreHostKey()

	return auth, nil
}
*/
